<template>
  <div>
    <div>
      <el-button type="primary" icon="el-icon-plus">新增数据</el-button>
    </div>
    <div>
      <div class="block">
        <el-tree
          :data="tableData"
          show-checkbox
          node-key="id"
          :default-expand-all="false"
          :expand-on-click-node="false"
          :render-content="renderContent"
        >
        </el-tree>
      </div>
    </div>
    <div>
      <el-dialog title="收货地址" :visible.sync="dialogFormVisible">
        <el-form :model="insertData">
          <el-form-item label="名称" :label-width="formLabelWidth">
            <el-input v-model="insertData.name" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="sureAdd()">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { treeList, deleteApi, insertApi } from "@/api/itemcat";
export default {
  data() {
    return {
      dialogFormVisible: false,
      formLabelWidth: "120px",
      tableData: [],
      insertData: {
        id: null,
        parentId: null,
        name: "",
        typeId: null,
      },
    };
  },
  created() {
    this.list();
  },
  methods: {
    sureAdd() {
      insertApi(this.insertData).then((result) => {
        this.list();
        this.dialogFormVisible = false;
        this.insertData.name = "";
        (this.insertData.id = null), (this.insertData.parentId = null);
      });
    },
    remove(node, data) {
      deleteApi(data.id);
      this.list();
    },
    append(data) {
      this.insertData.parentId = data.id;
      this.dialogFormVisible = true;
    },
    renderContent(h, { node, data, store }) {
      console.log(node);
      return (
        <span class="custom-tree-node">
          <span>{node.data.name}</span>
          <span>
            {node.level < 3 ? (
              <el-button
                size="mini"
                type="text"
                on-click={() => this.append(data)}
              >
                添加
              </el-button>
            ) : (
              ""
            )}
            <el-button
              size="mini"
              type="text"
              on-click={() => this.remove(node, data)}
            >
              删除
            </el-button>
          </span>
        </span>
      );
    },
    list() {
      treeList().then((result) => {
        this.tableData = result.data.data;
      });
    },
  },
};
</script>
<style>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
